package priv.sympsel.multiThreadDemo;

import java.util.concurrent.ArrayBlockingQueue;

class MyThreadPool {
    private ArrayBlockingQueue<Runnable> taskQueue;

    public MyThreadPool(int n) {
        // 初始化线程池
        taskQueue = new ArrayBlockingQueue<>(1000);
        // 创建n个线程
        for (int i = 0; i < n; i++) {
            new Thread(() -> {
                while (true) {
                    Runnable task;
                    try {
                        task = taskQueue.take();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    task.run();
                }
            }).start();
        }
    }

    public void submit(Runnable task) throws InterruptedException {
        // put 当队列满时会阻塞当前线程，直到队列有空间可用
        // offer 当队列满时会返回false
        taskQueue.put(task);
    }
}

class Demo3 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(5);
        for (int i = 0; i < 1000; i++) {
            int id = i;
            pool.submit(() -> {
                System.out.println(Thread.currentThread().getName() + ": " + id);
            });
        }
    }
}
